<template>
  <!-- 广告系列 -->
  <div v-loading="loading" class="flex bid-header" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading">

    <div class="appInfo flex">
      <div class="lt img">
        <el-image :src="appInfo.icon" style="height: 100%;width: 100%;" fit="cover">
          <div slot="error" class="image-slot flex" style="height: 100%;width: 100%;justify-content: center;background-color: #F5F7FA;">
            <i class="el-icon-picture-outline" style="font-size: 24px;color: #d9d9d9;" />
          </div>
        </el-image>
      </div>

      <div class="rt">
        <el-tooltip class="item" effect="dark" :content="cmName" placement="top-start">
          <p class="title webfont-Medium">
            <span class="overflow-ellipsis " style="max-width: 160px;font-size: 18px;margin: 0 auto 0 1px;line-height: 18px;">{{ cmName }}</span>
          </p>
        </el-tooltip>

        <p class="sub-title ">广告系列ID: {{ detail.campaignId }}</p>
      </div>
    </div>

    <div class="info-box flex">

      <div class="item status-box">
        <!-- 如果是删除了 -->
        <template v-if="detail.displayStatus=='DELETED'">
          <p class="sec" style="padding-top: 40px !important;">
            <i class="hui-color status-dot" /><span>已移除</span></p>
        </template>

        <!-- 否则 -->

        <template v-else>
          <template>
            <!-- 判断苹果状态 -->
            <template v-if="detail.displayStatus=='RUNNING'&&!detail.servingStateReasonsList">
              <p class="title">
                <!-- <em class="webfont-Medium" @click="handleSuspend">暂停</em> -->
                <el-switch v-if="editBtnShow" :value="true" active-color="#13ce66" @change="handleSuspend">
                </el-switch>
              </p>
              <p class="sec">
                <i class="liu-color status-dot" /><span>正在投放</span>
              </p>

            </template>
            <!-- 手动开启暂停 -->
            <template v-else-if="detail.displayStatus=='PAUSED'">
              <p class="title">
                <el-switch v-if="editBtnShow" :value="false" active-color="#13ce66" @change="handleOpen">
                </el-switch>
              </p>
              <p class="sec">
                <i class="yellow-color status-dot" /><span>已暂停</span>
              </p>
            </template>

            <!-- 因为别的原因被暂停 -->
            <template v-else>
              <div v-if="detail.servingStateReasons">
              <p v-if="detail.servingStateReasons.indexOf('TOTAL_BUDGET_EXHAUSTED')===-1" class="title">

                <el-switch v-if="editBtnShow&&detail.status!=='RUNNING'" :value="false" active-color="#13ce66" @change="handleOpen">
                </el-switch>
                <el-switch v-else :value="true" active-color="#13ce66" @change="handleSuspend">
                </el-switch>
              </p>
              <p v-else class="title" @click="editSeriesSet"><em v-if="editBtnShow" class="webfont-Medium">追加预算</em></p>
              </div>
              <el-tooltip placement="right" class="sec" style="padding-top: 0!important ;margin-top: 60px;">
                <div slot="content">
                  <p v-for="v in servingStateReasonsList" style="color: #fff;">{{ v }}</p>
                </div>
                <p class="pointer">
                  <i class="yellow-color status-dot" />
                  <span v-if="servingStateReasonsList&&servingStateReasonsList.length===1" class="webfont-Medium">{{ servingStateReasonsList[0] }}</span>
                  <span v-else-if="detail.displayStatus==='ON_HOLD'" class="webfont-Medium">暂缓</span>
                  <span v-else class="webfont-Medium">暂停</span>
                </p>
              </el-tooltip>
            </template>
          </template>
        </template>

      </div>

      <div v-if="countryData.length" class="item area">
        <country-popover v-if="countryData.length>1" :country-data="countryData" style="margin-bottom: 20px;">
          <span class="webfont-Medium pointer" style="font-size: 16px;">多个国家地区</span>
        </country-popover>

        <div v-else class="title" style="padding-bottom: 0px;margin-top: -10px;margin-bottom: 8px;">
          <div v-for="(item,index) in countryData" class="flex" style="justify-content: flex-start;">
            <country-flag :country="item.short" size="samll" />
            <span v-if="item">{{ item.name }}</span>
          </div>
        </div>
        <p class="sec">国家或地区</p>
      </div>
      <div v-if="detail.adchannelType" class="item position">
        <p class="title webfont-Bold">
          {{ detail.adchannelType==='SEARCH'?' 搜索结果':'“搜索”标签' }}
        </p>
        <p class="sec">投放位置</p>
      </div>

      <div class="item position">
        <p class="title webfont-Bold" v-if="detail.budgetAmount">
          {{ unitTxt }}{{ detail.budgetAmount|$toFixed(2) }}
        </p>
        <p v-else class="title webfont-Bold">-</p>
        <p class="sec">生命周期预算</p>
      </div>
      <div class="item position">
        <p class="title webfont-Bold">
          {{ unitTxt }}{{ detail.totalConsume|$toFixed(2) }}
        </p>
        <p class="sec">已消耗</p>
      </div>

      <div class="item position">
        <p class="title webfont-Bold">
			<template v-if="detail.dailyBudgetAmount!==null&&detail.dailyBudgetAmount!==undefined">{{ unitTxt }}{{ detail.dailyBudgetAmount|$toFixed(2) }}</template>
			<template v-else>-</template>

        </p>
        <p class="sec">每日预算上限</p>
      </div>

    </div>
    <div v-if="detail.displayStatus !=='DELETED'&&editBtnShow" class="handle">
      <em class="pointer" @click="editSeriesSet">修改广告系列设置</em>
    </div>

    <!-- 修改广告系列设置开始 -->
    <el-dialog title="修改广告系列设置" :visible.sync="dialogFormVisible" width="600px" class="bottom-dia">

      <el-form
        v-if="dialogFormVisible"
        ref="ruleForm"
        v-loading="editLoading"
        :model="form"
        label-position="top"
        class="form"
        size="small"
        :rules="rules"
        :element-loading-text="editLoadingTxt"
      >
        <el-form-item label="广告系列名称" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="countriesOrRegions">
          <div slot-name="label" class="label address flex" style="max-width: 500px;">
            <span class="webfont-Bold"><em style="color: red;">*</em> 选择投放国家/地区</span>
          </div>
          <country-select v-model="form.countriesOrRegions" :cities="cities" style="max-width: 500px;" />
        </el-form-item>
        <!-- <el-form-item label="预算" prop="budgetAmountNub">
          <amountInput
            v-if="(detail.orderState*1===0||detail.orderState===null||detail.orderState===undefined)&& (detail.orgId==='2810680'||detail.orgId==='2182520')"
            v-model="form.budgetAmountNub"
            title="广告系列未支付"
            :precision="2"
            :controls="false"
            :disabled="true"
          />
          <amountInput v-else v-model="form.budgetAmountNub" :precision="2" :controls="false" />
        </el-form-item> -->

        <template>
          <el-form-item label="每日预算上限" prop="dailyBudgetAmountNub">
            <amountInput v-model="form.dailyBudgetAmountNub" :controls="false" :precision="2" />
          </el-form-item>

        </template>

      </el-form>

      <!-- 增加预算开始 -->

      <el-dialog
        width="600px"
        title="追加预算"
        :visible.sync="innerVisible"
        append-to-body
        class="pay-add"
        :close-on-click-modal="false"
      >
        <div v-loading="payLoading" :element-loading-text="payLoadingTxt">
          <div class="box">
            <div class="title webfont-Bold">广告系列名称</div>
            <div class="info">{{ form.name }}</div>
          </div>
          <div class="box">
            <payDetails ref="addBudgetDetailBox" :num="addNum" type="add" @findAmountRes="findAmountResAdd" />
            <div v-if="orderInfo.ublance<needPayNum" class="pay-type" style="padding-bottom: 0px;">
              <div class="zfb active" @click="payType='zfb'">
                <img :src="zfbImg">
                <span>支付宝</span>
                <i class="el-icon-success" />
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" style="justify-content: flex-end;" class="flex">
          <el-button size="small" class="cancel-btn" @click="innerVisible = false">取 消</el-button>
          <el-button type="success" :disabled="addPayDisabled" size="small" @click="handlePayAdd">确定</el-button>
        </div>

      </el-dialog>

      <!-- 增加预算結束 -->

      <div slot="footer" class="dialog-footer flex">
        <em v-if="detail.displayStatus !=='DELETED'" class="btn-del pointer" style="font-size: 14px;" @click="delDiaShow=true">移除广告系列</em>
        <div>
          <el-button size="small" class="cancel-btn" @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="success" size="small" @click="goToPay">保存</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 修改广告系列设置结束 -->

    <el-dialog :visible.sync="newPaydShow" :title="'支付并开始投放'" width="600px" class="bottom-dia">
      <payDetails ref="payDetailBox" :num="detail.budgetAmount" @findAmountRes="findAmountRes" />
      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button size="small" class="cancel-btn" @click="newPaydShow=false">取 消</el-button>
        <el-button type="success" size="small" :disabled="payCaDisabled" @click="payCaOrder">去支付</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="delDiaShow" :title="'移除广告系列'" width="600px" class="del-dia">
      <div class="del-main">
        <i class="el-icon-warning el-icon"></i>
        <p class="title webfont-Medium">警告！移除广告系列属于永久性操作</p>
        <p class="sub-title">一旦移除便无法恢复或修改，历史记录报告仍可查看。
          冻结余额可能需5-10工作日后解冻。</p>
        <el-form
          ref="delForm"
          label-position="top"
          size="small"
          class="del-form"
          :model="delForm"
          :rules="delRules"
          @submit.native.prevent
        >
          <el-form-item prop="name" :label="'请输入“Delete”以移除,不区分大小写'">
            <el-input v-model="delForm.name" placeholder="请输入" @keyup.enter.native="handleBatchDel"></el-input>
          </el-form-item>
        </el-form>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" class="cancel-btn" @click="delDiaShow=false">取 消</el-button>
        <el-button type="success" size="small" @click="handleBatchDel">确定</el-button>
      </div>
    </el-dialog>

  </div>

  <!-- Form -->

</template>

<script>
import payDetails from '@/components/payDetails/index.vue'
import countrySelect from '@/components/countrySelect/index.vue'
import amountInput from '@/components/amountInput/index.vue'
import countryPopover from '@/components/countryPopover/index.vue'

import {
  removeCampaign, // 删除广告系列
  modifyCampaign // 修改广告系列的设置
} from '@/api/overView.js'

import {
  findCountryByQuery
} from '@/utils/index.js'
import {
  findCampaignOne,
  searchApps,
  isEmptyName,
  OrderPayment, // 创建支付订单之后付款
  findMaxOne
} from '@/api/create.js' //

import {
  createCustomer // 创建一个支付订单
} from '@/api/finace.js'

import {
  servingStateReasonscp
} from '@/utils/servingStateReasons.js'

import {
  servingStateReasonsad
} from '@/utils/servingStateReasons.js'

export default {
  components: {
    payDetails,
    countrySelect,
    amountInput,
    countryPopover

  },

  props: {

  },

  data() {
    const validateIsName = (rule, value, callback) => {
      const str = 'Delete'
      if (!value) {
        callback(new Error('请输入“Delete”以移除,不区分大小写'))
      } else if (value.trim().toLowerCase() !== str.toLowerCase()) {
        callback(new Error('请输入“Delete”以移除,不区分大小写'))
      } else {
        callback()
      }
    }
    return {
      originalId: undefined, // 广告系列原始拼接的
      unitTxt: '',
      /* '金额显示符号' */
      newPaydShow: false, // 未支付的广告系列的支付窗口显示
      payCaDisabled: true, // 未支付的广告系列的支付按钮状态
      appInfo: {
        icon: undefined
      },
      addPayDisabled: true, // 追加预算保存
      orderId: undefined, // 支付订单好
      orderInfo: {}, // 用户余额，汇率，服务费率等
      loading: true,
      loadingText: '数据获取中，请稍后',
      editLoading: false,
      editLoadingTxt: '数据提交中，请稍后',
      payLoading: false,
      payLoadingTxt: '数据创建中，请稍后',
      zfbImg: require('@/assets/images/icon/zfb.svg'), // 支付宝icon
      lineImg: require('@/assets/images/icon/line-pay.svg'), // 线下付款icon
      innerVisible: false,
      cmName: undefined, // 广告系列的名称
      num: 0,
      detail: {},
      countryData: [], // 广告系列已经选择好的一些国家
      cities: [], // app可选的一些国家
      dialogFormVisible: false,
      form: {
        name: undefined,
        dailyBudgetAmountNub: 0, // 每日预算
        countriesOrRegions: []
      },

      formCopy: {}, // 对比数据是否有修改
      // 删除广告系列需要的数据
      delDiaShow: false,
      delForm: {
        name: ''
      },

      delRules: {
        name: [{
          required: true,
          message: '请输入“Delete”以移除,不区分大小写',
          trigger: 'blur'
        }, {
          validator: validateIsName,
          trigger: 'blur'
        }

        ]
      }

    }
  },
  computed: {
    // 选择的时区
    timeZone() {
      return this.$store.state.user.timeZone
    },
    servingStateReasonsList() {
      if (this.detail.servingStateReasons && this.detail.servingStateReasons.length) {
        return servingStateReasonscp(this.detail.servingStateReasons)
      } else {
        return []
      }
    },

    editBtnShow() {
      if (this.$route.query.uuid && (this.$route.query.orgId || this.$route.query.orgid)) {
        const index = this.$store.state.overview.allAc.findIndex(item => {
          return item.uuid === this.$route.query.uuid
        })
        if (this.$store.state.overview.allAc[index].roleName === 'invalid_client' || this.$store.state.overview.allAc[
          index].roleName === 'API Read Only') {
          return false
        }

        const i = this.$store.state.overview.allAc[index].org.findIndex(item => {
          return item.orgId === this.$route.query.orgId * 1 || item.orgId === this.$route.query.orgid * 1
        })
        const orgRole = this.$store.state.overview.allAc[index].org[i].roleName
        return orgRole !== 'API Read Only' && orgRole !== 'invalid_client' && !this.$isReadOnly(this.$store.state.user
          .userInfo.roleName)
      } else {
        return !this.$isReadOnly(this.$store.state.user.userInfo.roleName)
      }
    },

    // 追加预算计算
    addNum() {
      if (this.form.budgetAmountNub) {
        const num = ((this.form.budgetAmountNub * 100) - (this.detail.budgetAmount * 100)) / 100
        const amount = num.toFixed(2)
        return amount
      } else {
        return 0.00
      }
    },
    // 需要支付的金额；人民币换算
    needPayNum() {
      if (this.orderInfo.endamount && this.orderInfo.exrate) {
        const amount = (this.orderInfo.endamount * this.orderInfo.exrate).toFixed(2)
        return amount
      } else {
        return NaN
      }
    },
    dailyBudgetAmountNubIsrequired() {
      if (!this.formCopy.dailyBudgetAmountNub) return false
      return true
    },

    rules() {
      // // 每日预算验证
      const validateDailyBudgetAmountNub = async(rule, value, callback) => {
        const minNum = await this.findMaxOne()
          if (!value|| value * 100 < 1) {
            callback(new Error('你的每日预算上限必须至少为0.01 且不得超过广告系列预算'))
          } else if (value * 100 < minNum * 100) {
            callback(new Error('每日预算不能低于该广告系列的关键词/单次点击费用最高价' + minNum.toFixed(2)))
          } else {
            callback()
          }
      }

      // 预算验证
      const validatebudgetAmountNub = (rule, value, callback) => {
        // alert(value < this.detail.budgetAmountNub,this.detail)
        if (!value) {
          callback(new Error('不能为空'))
        } else if (value > 20000000 || value * 100 < 1) {
          callback(new Error('你的预算必须至少为0.01 且不得超过 20,000,000.00'))
        } else if (value < this.detail.budgetAmount) {
          callback(new Error('总预算不能少于您之前设定的的值' + this.detail.budgetAmount))
        } else {
          callback()
        }
      }

      const validateName = async(rule, value, callback) => {
        if (value === this.cmName) {
          callback()
        } else {
          const query = {
            campaignName: value,
            orgId: this.$route.query.orgId || '', // 如果是自助投放为空
            uuid: this.$route.query.uuid || '',
            aId: this.$route.query.aId || this.$route.query.aid || '',
            appid: '',
            currencyType: this.$route.query.currencyType || this.$store.state.user.unit,
            teamId: this.$store.state.team.teamId
          }
          const res = await isEmptyName(query)
          if (res.data.code === 20000 && !res.data.data.length) {
            callback()
          } else {
            callback(new Error('广告系列名称重复'))
          }
        }
      }
      const obj = {
        name: [{
          required: true,
          message: '请输入活动名称',
          trigger: 'blur'
        },
        {
          validator: validateName,
          trigger: 'blur'
        }
        ],
        countriesOrRegions: [{
          required: true,
          message: '请选择投放国家/地区',
          trigger: 'change'
        }],
        dailyBudgetAmountNub: [{
          validator: validateDailyBudgetAmountNub,
          trigger: 'blur'
        }]

      }
      return obj
    }

  },
  watch: {
    timeZone: {
      deep: true,
      handler: function(newV, oldV) {
        this.findCampaignOne()
      }
    }
  },

  mounted() {
    this.unitTxt = this.$store.state.user.unit === 'USD' ? '$' : '￥'
    this.findCampaignOne()
  },
  methods: {
    async handleBatchDel() {
      this.$refs['delForm'].validate(async(valid) => {
        if (valid) {
          const arr = [{
            teamId: this.$store.state.team.teamId || '',
            orgId: this.$route.query.orgId ? this.$route.query.orgId.toString() : '', // 如果是自助投放为空
            uuid: this.$route.query.uuid || '',
            aId: this.$route.query.aId || this.$route.query.aid || '',
            campaignId: this.detail.campaignId,
            campaignGroupId: this.detail.campaignGroupId,
            currencyType: this.$store.state.user.unit
          }]

          const res = await removeCampaign(arr)

          if (res.data.code === 20000) {
            this.$refs['delForm'].resetField && this.$refs['delForm'].resetField()
            this.$nextTick(() => {
              this.delDiaShow = false
              this.dialogFormVisible = false
            })

            this.findCampaignOne()
            this.$emit('changeStatus')
            this.$store.dispatch('overview/getAllCampaign', {
              teamId: this.$store.state.team.teamId || '',
              orgId: this.$route.query.orgId || '', // 如果是自助投放为空
              uuid: this.$route.query.uuid || '',
              aId: this.$route.query.aId || this.$route.query.aid || '',
              campaignId: this.$route.query.campaignId,
              campaignGroupId: this.$route.query.serialId || '',
              appid: '',
              currencyType: this.$store.state.user.unit,
              campaignGroupId: this.$route.query.serialId || 0
            })
            this.$message.closeAll()
            this.$message({
              message: res.data.message || '操作成功，正在刷新数据',
              type: 'success'
            })
          } else {
            this.$message.closeAll()
            this.$message.error(res.data.message || '服务器出现错误')
          }
        } else {
          return
        }
      })
    },
    findAmountRes(payData) {
      if (payData.ublance * 100 < payData.endamount * 100) return false
      return this.payCaDisabled = false
    },
    findAmountResAdd(payData) {
      if (payData.ublance * 100 < payData.endamount * 100) return false
      return this.addPayDisabled = false
    },

    async findMaxOne() {
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        campaignId: this.$route.query.campaignId,
        currencyType: this.detail.budgetCurrency || this.$store.state.user.unit,
        campaignGroupId: this.$route.query.serialId || ''
      }
      const res = await findMaxOne(obj)
      return res.data.data * 1
    },

    handlePayCa() {
      this.newPaydShow = true
      this.payCaDisabled = true
      this.$nextTick(() => {
        this.$refs.payDetailBox.findAmountPayable()
      })
    },

    // 根据orgid、campaignId查询某个Campaign详情
    async findCampaignOne() {
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        campaignId: this.$route.query.campaignId,
        campaignGroupId: this.$route.query.serialId || '',
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime

      }

      const allCa = this.$store.state.overview.allCa
      const index = allCa.findIndex(item => {
        return item.campaignId * 1 === obj.campaignId * 1
      })

      const countryArr = findCountryByQuery(allCa[index].countriesOrRegions, true)
      const strArr = countryArr.map(item => {
        return item.short
      })
      obj.country = strArr.join(',')
      // obj.currencyType = allCa[index].budgetCurrency
       obj.currencyType = this.$store.state.user.unit
      this.loading = true
      this.loadingText = '广告系列数据获取中'
      const res = await findCampaignOne(obj)

      if (res.data.code === 20000) {
        this.detail = res.data.data
        this.$store.dispatch('overview/editOneCa', res.data.data)
        if (this.$route.query.modelType === 'self-help') {
          const index = this.detail.name.indexOf('_3YData_')
          var str = this.detail.countriesOrRegions.substr(1)
          var str1 = str.substr(0, str.length - 1)

          this.cmName = this.detail.name.slice(index + 8)
          this.originalId = this.detail.name.slice(0, index + 8)
        } else {
          this.cmName = this.detail.name
        }
        // 处理国家
        const countryData = findCountryByQuery(this.detail.countriesOrRegions, true)
        this.countryData = countryData
        this.form.countriesOrRegions = countryData.map(item => {
          return item.short
        })
        // 每日预算上限
        this.num = this.detail.dailyBudgetAmount
        this.searchApps()
        this.loading = false
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误，请稍后重试')
      }
    },

    // 获取appid的具体信息并设置可选的国家
    async searchApps() {
      const id = this.detail.adamId
      const res = await searchApps(id)
      if (res.data.code === 20000) {
        // 存储起来
        this.appInfo = res.data.data.length > 0 ? JSON.parse(JSON.stringify(res.data.data[0])) : ''
        this.cities = res.data.data.length > 0 ? res.data.data[0].countryOrRegionCodes : ''
      } else {
        this.cities = JSON.parse(JSON.stringify(this.form.countriesOrRegions))
      }
    },

    async handleOpen() {
      this.editLoading = true
      this.loading = true
      this.editLoadingTxt = '设置提交中，请稍候'
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        currencyType: this.detail.budgetCurrency || this.$store.state.user.unit,
        campaignId: this.detail.campaignId,
        campaignGroupId: this.detail.campaignGroupId,
        userId: this.$store.state.user.userInfo.userId,
        uuid: this.$route.query.uuid || '', // 自助投放为空
        orgId: this.$route.query.orgId || '', // 自助投放为空
        aId: this.$route.query.aId || this.$route.query.aid || '',
        updateCampaign: {
          campaign: {
            status: 'ENABLED'
          }

        }
      }

      this.modifyCampaign(obj)
    },
    async handleSuspend() {
      this.editLoading = true
      this.loading = true
      this.editLoadingTxt = '设置提交中，请稍候'
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        currencyType: this.detail.budgetCurrency || this.$store.state.user.unit,
        campaignId: this.detail.campaignId,
        campaignGroupId: this.detail.campaignGroupId,
        userId: this.$store.state.user.userInfo.userId,
        uuid: this.$route.query.uuid || '', // 自助投放为空
        orgId: this.$route.query.orgId || '', // 自助投放为空
        aId: this.$route.query.aId || this.$route.query.aid || '',
        updateCampaign: {
          campaign: {
            status: 'PAUSED'
          }

        }
      }

      this.modifyCampaign(obj)
    },

    // 点击了修改广告系列设置按钮
    editSeriesSet() {
      const index = this.detail.name.indexOf('_3YData_')
      const countryData = this.countryData.map(item => {
        return item.short
      })

      var name = undefined
      if (!this.$route.query.modelType || this.$route.query.modelType === 'self-help') {
        this.cmName = this.detail.name.slice(index + 8)
        name = this.detail.name.slice(index + 8)
      } else {
        this.cmName = this.detail.name
        name = this.detail.name
      }

      const obj = {
        name,
        dailyBudgetAmountNub: this.detail.dailyBudgetAmount == null ? undefined : this.detail.dailyBudgetAmount * 1,
        countriesOrRegions: countryData
      }

      this.form = JSON.parse(JSON.stringify(obj))
      this.$set(this.form, 'countriesOrRegions', countryData)
      // 方便到时候对比数据
      this.formCopy = JSON.parse(JSON.stringify(this.form))
      this.dialogFormVisible = true

      this.$nextTick(() => {
        this.$forceUpdate()
        this.$refs['ruleForm'].clearValidate()
      })
    },

    // 点击了修改设置的保存接口  判断需不需要显示追加预算弹窗；
    goToPay() {
      this.orderId = undefined
      this.orderInfo = {}
      // 数据是否有修改
      let numFalg = true

      // 判断国家是否有修改
      var falg = this.form.countriesOrRegions.every(item => {
        const index = this.formCopy.countriesOrRegions.indexOf(item)
        return index !== -1
      })

      if (falg) {
        falg = this.formCopy.countriesOrRegions.every(item => {
          const index = this.form.countriesOrRegions.indexOf(item)
          return index !== -1
        })
      }

      // 判断名称是否有修改
      if (this.form.name !== this.formCopy.name) {
        falg = false
      }

      // 判断总预算是否有修改
      if (this.form.budgetAmountNub * 100 !== this.formCopy.budgetAmountNub * 100) {
        falg = false
        if (this.detail.orgId === '2810680' || this.detail.orgId === '2182520') {
          numFalg = false
        }
      }

      // 判断每日预算是否有修改
      if (this.form.dailyBudgetAmountNub * 100 !== this.formCopy.dailyBudgetAmountNub * 100) {
        falg = false
      }

      if (falg) {
        // 全部都没有修改
        this.dialogFormVisible = false
      } else {
        // 显示追加预算接口
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if (numFalg) {
              this.handleSubEdit()
            } else {
              this.addPayDisabled = true
              this.innerVisible = true
              this.$nextTick(() => {
                this.$refs['addBudgetDetailBox'].findAmountPayable()
              })
            }
          } else {
            this.$messgae.closeAll()
            this.$messgae.error('请完善信息')
            return false
          }
        })
      }
    },

    // 点击了提交修改广告系列设置
    handleSubEdit() {
      this.editLoading = true
      this.editLoadingTxt = '数据提交中，请稍候'
      const countriesOrRegions = this.form.countriesOrRegions.map(item => {
        return item.trim()
      })
      var name = undefined
      if (!this.$route.query.modelType || this.$route.query.modelType === 'self-help') {
        name = this.originalId + this.form.name
      } else {
        name = this.form.name
      }
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        currencyType: this.detail.budgetCurrency || this.$store.state.user.unit,
        campaignId: this.detail.campaignId,
        campaignGroupId: this.detail.campaignGroupId,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        userId: this.$store.state.user.userInfo.userId,
        updateCampaign: {
          campaign: {
            dailyBudgetAmountNub: this.form.dailyBudgetAmountNub ? this.form.dailyBudgetAmountNub : 0,
            name,
            countriesOrRegions
          }
        }
      }

      if (this.orderId) {
        obj.orderId = this.orderId
      }

      if (this.detail.orgId !== '2810680' && this.detail.orgId !== '2182520') {
        obj.updateCampaign.campaign.budgetAmountNub = this.form.budgetAmountNub
      }

      this.modifyCampaign(obj)
    },

    // 修改广告系列的设置
    async modifyCampaign(data) {
      const res = await modifyCampaign([data])
      this.editLoading = false

      if (res.data.code && res.data.code === 20000) {
        this.$message({
          message: res.data.message || '服务器错误，请稍后重试',
          type: 'success'
        })
        this.loading = true
        this.loadingText = '数据更新中，请稍候'
        this.dialogFormVisible = false
        setTimeout(() => {
          this.findCampaignOne()
          this.$emit('changeStatus')
        }, 7000) // 更新数据  有延迟
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误，请稍后重试')
      }
    },

    // 确定追加预算
    async handlePayAdd() {
      const order = await this.createCustomer()
      if (!order) return false

      this.payLoadingTxt = '订单支付中，请稍候'
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        order: this.orderId,
        uid: this.$store.state.user.userInfo.userId,
        url: encodeURIComponent(window.location.href),
        campaignId: this.detail.campaignId,
        campaignGroupId: this.detail.campaignGroupId,
        CAmountNub: this.addNum
      }

      const countriesOrRegions = this.form.countriesOrRegions.map(item => {
        return item.trim()
      })

      const adv = {
        currencyType: this.$route.query.unit || this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId || '',
        campaignId: this.$route.query.campaignId,
        campaignGroupId: this.detail.campaignGroupId,
        orgId: '',
        uuid: '',
        userId: this.$store.state.user.userInfo.userId,
        updateCampaign: {
          campaign: {
            ...this.form,
            name: this.originalId + this.form.name,
            countriesOrRegions
          }
        }
      }
      obj.adv = JSON.stringify(adv)
      this.orderPayment(obj)
    },

    // 创建追加预算订单
    async createCustomer() {
      this.payLoading = true
      this.payLoadingTxt = '订单创建中，请稍候'

      const obj = {
        teamId: this.$store.state.team.teamId || '',
        userId: this.$store.state.user.userInfo.userId,
        amount: ((this.form.budgetAmountNub * 100) - (this.formCopy.budgetAmountNub * 100)) / 100,
        type: this.$store.state.user.unit
      }
      const res = await createCustomer(obj)
      if (res.data.code === 20000) {
        this.createFlag = true
        this.orderId = res.data.data.order
        return res.data.data
      } else {
        this.createFlag = false
        this.payLoading = false
        this.$message.closeAll()
        this.$message.error(res.data.message || '创建订单失败，请稍后重试')
        return false
      }
    },

    // 支付未付款的广告系列预算
    payCaOrder() {
      const {
        campaignId,
        order
      } = this.detail
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        campaignId,
        order,
        uid: this.$store.state.user.userInfo.userId,
        url: encodeURIComponent(window.location.href)
      }

      this.orderPayment(obj)
    },

    // 支付订单  追加预算
    async orderPayment(data) {
      const res = await OrderPayment(data)

      if (res.data.code === 20000) {
        // 余额不足的情况下
        if (res.data.message.indexOf('不足') !== -1 || res.data.message.indexOf('支付宝') !== -1) {
          this.$message.closeAll()
          if (this.$store.state.user.userInfo.roleName !== 'admin' && this.$store.state.user.userInfo.roleName !==
              'visitor') {
            this.payLoading = false
            this.innerVisible = false
            this.dialogFormVisible = false
            return this.$message.error('余额不足，请联系管理员')
          } else {
            this.payLoading = false
            this.innerVisible = false
            this.dialogFormVisible = false
            this.$message.error('余额不足，请使用支付宝支付')
          }
          const div = document.createElement('div')
          const idName = 'aliPayForm' + new Date().getTime()
          div.id = idName
          div.innerHTML = res.data.data
          document.body.appendChild(div)
          const aliPayFormBox = document.querySelector('#' + idName + ' form')
          aliPayFormBox.submit()
          this.$router.replace({
            path: this.$route.path,
            query: this.$route.query
          })
        } else {
          this.$message.closeAll()
          this.$message({
            duration: 1500,
            message: res.data.message || '支付成功',
            type: 'success'
          })
          this.payLoading = false
          this.innerVisible = false
          this.dialogFormVisible = false
          this.newPaydShow = false
          this.loading = true
          this.loadingText = '数据更新中，请稍候'
          setTimeout(() => {
            this.findCampaignOne()
            this.$emit('changeStatus')
          }, 7000) // 更新数据  有延迟
        }
      } else {
        this.payLoading = false
        this.$message.closeAll()
        this.$message.error(res.data.message || '支付失败，请稍后重试')
      }
    }
  }
}
</script>

<style lang="scss" scoped="true">
  @import './styles/index.scss';

  .form {

    .el-select,
    .el-input-number,
    ::v-deep .el-form-item__content,
    .el-input,
    .el-input__inner {
      width: 100%;
      max-width: 500px;
    }

    .el-form-item::v-deep .el-input-number input {
      text-align: left;
    }

    .el-form-item::v-deep .el-input-number .el-input {
      position: relative;
    }
  }

  .pay-add .box {
    margin-bottom: 24px;

    .title {
      color: rgba(57, 68, 78, 0.8);
      margin-bottom: 14px;
      text-align: left;
      font-style: normal;
    }

    .info {
      color: rgba(57, 68, 78, 1);
      text-align: left;
    }

    .info ul {
      border: 1px solid rgba(0, 0, 0, 0.1);
      border-radius: 4px;

      li {
        border-top: 1px solid rgba(0, 0, 0, 0.1);
        min-height: 46px;
        line-height: 46px;
        background: rgba(229, 229, 229, 0.5);

        &:first-of-type {
          border: none;
        }

        .title {
          color: rgba(57, 68, 78, 1);
          margin: 0;
          width: 140px;
          padding-left: 24px;
          font-size: 15px;
        }

        .num {
          flex: 1;
          background-color: #FFFFFF;
          color: rgba(57, 68, 78, .8);
          border-left: 1px solid rgba(0, 0, 0, 0.1);
          padding-right: 24px;
          text-align: right;

          span {
            padding-top: 8px;
            display: block;
            line-height: 24px;
            color: rgba(57, 68, 78, 1);
          }

          .dec {
            padding: 0;
            margin-top: -6px;
            padding-bottom: 8px;
            font-size: 12px;
            font-weight: 400;
            color: #ACB6C2;
          }
        }
      }
    }
  }

  .pay-type {
    display: flex;
    padding: 24px 0;
    padding-top: 32px;

    div {
      width: 184px;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 28px;
      border: 1px solid #BDC5CB;
      cursor: pointer;
      border-radius: 6px;

      img {
        width: 32px;
        height: 32px;
      }

      span {
        font-size: 16px;
        margin: 0 24px;
      }

      i {
        font-size: 24px;
        color: $mainColor1;
        display: none;
      }

      &.active {
        border: 1px solid $mainColor1;

        i {
          display: inline-block;
        }
      }
    }
  }

  .appInfo {
    .lt.img {
      width: 64px;
      height: 64px;
      border-radius: 2px;
      overflow: hidden;
      margin-right: 16px;
    }

    .rt {
      .title {
        font-style: normal;
        font-size: 16px;
        line-height: 16px;
        color: #39444E;
        margin-bottom: 20px;
      }

      .sub-title {
        font-style: normal;
        font-weight: normal;
        font-size: 12px;
        line-height: 12px;
        /* identical to box height, or 129% */
        color: #ACB6C2;

      }
    }
  }

  .status-box {
    padding-left: 14px;

    .title {
      font-size: 14px !important;
      cursor: pointer;
      padding-bottom: 0px !important;
      margin-bottom: -36px;
      position: relative;
      z-index: 2;
    }

    .sec {
      padding-top: 56px !important;
    }

    span {
      font-size: 14px;
    }
  }

  .del-dia {
    .del-main {
      padding-top: 20px;
      padding-bottom: 30px;
      text-align: center;

      .el-icon {
        color: #FAAD14;
        font-size: 40px;
      }

      .title {
        padding-top: 20px;
        padding-bottom: 12px;
        font-size: 20px;
        line-height: 20px;
        color: #1D2129;
      }

      .sub-title {
        margin: 0 auto;
        margin-bottom: 20px;
        width: 400px;
        font-weight: 400;
        font-size: 14px;
        line-height: 24px;
        /* or 171% */
        text-align: center;
        color: rgba(51, 64, 74, 0.8);
      }

      .del-form {
        width: 258px;
        margin: 0 auto;
      }
    }
  }

.el-dialog__wrapper /deep/   .el-form--label-top .el-form-item__label {
    line-height: 14px;
  }

 .el-dialog__wrapper /deep/ .el-form-item--mini.el-form-item,
 .el-dialog__wrapper /deep/  .el-form-item--small.el-form-item {
    margin-bottom: 26px;
  }

  .el-dialog__wrapper /deep/ .el-form-item--small .el-form-item__error {
    padding-top: 4px;
  }
</style>
